import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/LoginView.vue'),
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/components/common/AppLayout.vue'),
    redirect: '/users',
    meta: { requiresAuth: true },
    children: [
      {
        path: '/users',
        name: 'UserManagement',
        component: () => import('@/views/UserManagement.vue'),
        meta: {
          title: '用户管理',
          icon: 'user',
          breadcrumb: ['首页', '用户管理']
        }
      },

      {
        path: '/shops',
        name: 'ShopManagement',
        component: () => import('@/views/ShopManagement.vue'),
        meta: {
          title: '店铺管理',
          icon: 'shop',
          breadcrumb: ['首页', '店铺管理']
        }
      },
      {
        path: '/scenics',
        name: 'ScenicManagement',
        component: () => import('@/views/ScenicManagement.vue'),
        meta: {
          title: '景区管理',
          icon: 'scenic',
          breadcrumb: ['首页', '景区管理']
        }
      },
      {
        path: '/messages',
        name: 'MessageManagement',
        component: () => import('@/views/MessageManagement.vue'),
        meta: {
          title: '留言板管理',
          icon: 'message',
          breadcrumb: ['首页', '留言板管理']
        }
      },
      {
        path: '/reservations',
        name: 'ReservationManagement',
        component: () => import('@/views/ScenicOrderView.vue'),
        // component: () => import('@/views/ReservationManagement.vue'),
        meta: {
          title: '景点预约管理',
          icon: 'reservation',
          breadcrumb: ['首页', '景点预约管理']
        }
      },
      // {
      //   path: 'scenic-orders',
      //   name: 'scenicOrders',
      //   component: () => import('@/views/ReservationManagement.vue'),
      //   // component: () => import('@/views/ScenicOrderView.vue'),
      //   meta: {
      //     requiresAuth: true,
      //     title: '景点订单管理',
      //     icon: 'Document',
      //     breadcrumb: ['首页', '景点订单管理']
      //   }
      // }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '页面未找到' }
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // 路由切换时滚动到顶部
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫 - 设置页面标题和认证检查
router.beforeEach((to, from, next) => {
  // 设置页面标题
  if (to.meta && to.meta.title) {
    document.title = `${to.meta.title} - 福州印象管理后台`
  } else {
    document.title = '福州印象管理后台'
  }

  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    const userInfo = localStorage.getItem('userInfo')

    if (!token || !userInfo) {
      // 未登录，重定向到登录页面
      next({ name: 'Login' })
      return
    }

    try {
      // 验证token有效性（这里可以添加实际的token验证逻辑）
      const user = JSON.parse(userInfo)
      if (!user.id || !user.username) {
        throw new Error('用户信息无效')
      }
    } catch (error) {
      // 用户信息无效，清除存储并重定向到登录
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      next({ name: 'Login' })
      return
    }
  }

  // 如果已经登录但访问登录页面，重定向到首页
  if (to.name === 'Login') {
    const token = localStorage.getItem('token')
    if (token) {
      next({ path: '/' })
      return
    }
  }

  next()
})

// 全局后置钩子 - 页面加载完成后的处理
router.afterEach((to, from) => {
  // 可以在这里添加页面访问统计等逻辑
  console.log(`导航到: ${to.path}`)
})

export default router
